package com.pm.web.controller.api;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pm.buglist.domain.Project;
import com.pm.buglist.domain.WavieOrder;
import com.pm.buglist.service.ProjectService;
import com.pm.buglist.service.WavieOrderService;
import com.pm.common.OAService;
import com.pm.common.annotation.Log;
import com.pm.common.config.ParamConfig;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.domain.entity.SysUser;
import com.pm.common.enums.BusinessType;
import com.pm.common.utils.*;
import com.pm.system.mapper.SysUserMapper;
import com.pm.system.service.ISysConfigService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/business/api")
public class ApiController extends BaseController {

    @Resource
    private ISysConfigService configService;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private OaVliTokenUtils oaVliTokenUtils;

    @Resource
    private ProjectService projectService;

    @Resource
    private WeChatNoteUtils weChatNoteUtils;

    @Resource
    private ParamConfig paramConfig;



    @Resource
    private WavieOrderService wavieOrderService;

    @Resource
    private OaUtils oaUtils;


    @Resource
    private OAService oaService;

    /**
     * 验证oa登录令牌接口
     *
     * */
    @GetMapping("/getSource/{ticket}")
    public AjaxResult getFromSource(@PathVariable("ticket") String ticket,HttpServletRequest request){
        SysUser user =new SysUser();
        if(!StringUtils.isEmpty(ticket)){
            //不为空验证token
            String sn = oaVliTokenUtils.vliTicket(ticket);
            if(!StringUtils.isEmpty(sn)){//验证成功
                //验证成功，获取到用户信息
                String jobNumber=sn;
                //根据工号获取用户信息
                user = userMapper.getUserInfoByJobNumber(jobNumber);
            }
        }
        //验证成功如果查询的用户为空/或者验证成功查询不到对应的用户信息（也是游客角色）
        if(ObjectUtils.isEmpty(user)){
            //查询系统游客账号的工号
            String visJn = configService.selectConfigByKey("visitor_jn");
            //根据工号获取用户信息
            user = userMapper.getUserInfoByJobNumber(visJn);
        }
        //返回用户信息
        return  AjaxResult.success(user);
    }

    /**
     * 同步oa测试项目表单接口
     * */
    @PostMapping("/OaProjectFormData")
    @Log(title = "外部接口:同步oa测试项目表单接口", businessType = BusinessType.INSERT,isExternalRequest = true)
    public AjaxResult synchronousOaFromData(@RequestBody JSONObject jsonObject){
        //获取到oa同步过来的数据、封装成project数据
        Project project =JSONObject.parseObject(jsonObject.toString(),Project.class);
        try {
            String oaUser = configService.selectConfigByKey("OA_USER");
            Long oaUid = Long.valueOf(oaUser);
            project.setAddUser(oaUid);//设置添加数据来源
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("同步oa系统测试项目数据添加项目数据来源失败！！"+e.getMessage());
        }

        //插入数据
        AjaxResult ajaxResult = projectService.OaInsertProject(project);
        if(ajaxResult.isSuccess()){
            logger.info("同步oa测试项目数据成功");
            return ajaxResult;
        }else {
            //获取企业微信消息通知对象
            String noteUser = configService.selectConfigByKey("NOTE_USER");
            if(!StringUtils.isEmpty(noteUser)){
                new Thread(()->{
                    String[] userNum = noteUser.split(",");
                    List<String> list = Arrays.asList(userNum);
                    String msg="同步oa测试项目数据失败提醒,同步失败的项目数据为："+jsonObject;
                    String msg1="请你尽快登录bugList系统进行处理，谢谢。系统登录链接为："+paramConfig.getLink();
                    List<String> message=new ArrayList<>();
                    message.add(msg);
                    message.add(msg1);
                    weChatNoteUtils.sendWeChatNoteByJobNumber(list,message);
                }).start();
            }
            logger.error("同步oa测试项目数据失败:"+ajaxResult+";\n项目数据为:"+jsonObject);
            return AjaxResult.error("同步oa测试项目数据失败:"+ajaxResult.get("msg"));
        }
    }

    /**
     * waive单签核状态回写接口
     * @param jsonObject
     */
    @Log(title = "外部接口:回写OA waive单签核审批流程状态", businessType = BusinessType.UPDATE,isExternalRequest = true)
    @PostMapping("/waiveBackStatus")
    public void waiveBackStatus(@RequestBody JSONObject jsonObject){
        try {
            //获取参数
            String oaId = jsonObject.getString("oaId");//流程id
            String status = jsonObject.getString("status");//状态
            String opinions = jsonObject.getString("approvalOpinions");//审批意见

            if(!StringUtils.isEmpty(oaId)){//oa_id不能为空
                QueryWrapper<WavieOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("oa_id",oaId);
                WavieOrder wavieOrder = new WavieOrder();
                wavieOrder.setOaStatus(status);//状态
                wavieOrder.setOaResult(opinions);//审批意见
                wavieOrderService.update(wavieOrder,queryWrapper);//修改状态
                logger.info("waive单签核状态回写成功！");
            }else {
                logger.error("waive单流程签核流程ID为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("waive单签核状态回写异常,"+"请求参数为:"+jsonObject+",\n"+e);
        }

    }


    /**
     * 项目附件审核回调接口
     * @param jsonObject
     */
    @Log(title = "外部接口:项目附件审核回调接口", businessType = BusinessType.UPDATE,isExternalRequest = true)
    @PostMapping("/projectFileProcessBackStatus")
    public AjaxResult projectFileProcessBackStatus(@RequestBody JSONObject jsonObject){
         if(StringUtils.isBlank(jsonObject.getString("oaId")) || jsonObject.getInteger("status") == null){
             return error("请求参数错误，缺少ID或状态");
         }
         oaService.projectFileProcessBackStatus(jsonObject);
         return success("操作成功!");
    }


    /**
     * 多人审核任务通过状态回写接口
     * @param jsonObject
     */
    @Log(title = "外部接口:多人审核任务状态回写接口", businessType = BusinessType.UPDATE,isExternalRequest = true)
    @PostMapping("/projectFileMoreBackStatus")
    public AjaxResult projectFileMoreBackStatus(@RequestBody JSONObject jsonObject) throws IOException {
        if(StringUtils.isBlank(jsonObject.getString("oaId")) || jsonObject.getInteger("status") == null){
            return error("请求参数错误，缺少ID或状态");
        }
        oaService.projectFileMoreBackStatus(jsonObject);
        return success("操作成功!");
    }


    /**
     * 多人审核任务驳回状态回写接口
     * @param jsonObject
     */
    @Log(title = "外部接口:多人审核任务驳回回写接口", businessType = BusinessType.UPDATE,isExternalRequest = true)
    @PostMapping("/projectFileMoreRejectBack")
    public AjaxResult projectFileMoreRejectBack(@RequestBody JSONObject jsonObject) throws IOException {
        if(StringUtils.isBlank(jsonObject.getString("oaId"))){
            return error("请求参数错误，缺少ID或状态");
        }
        oaService.projectFileMoreBackStatus(jsonObject);
        return success("操作成功!");
    }


    /**
     * 多人审核任务结束状态回写接口
     * @param jsonObject
     */
    @Log(title = "外部接口:多人审核任务结束状态回写接口", businessType = BusinessType.UPDATE,isExternalRequest = true)
    @PostMapping("/projectFileMoreEndBackStatus")
    public AjaxResult projectFileMoreEndBackStatus(@RequestBody JSONObject jsonObject){
        if(StringUtils.isBlank(jsonObject.getString("oaId"))){
            return error("请求参数错误，缺少ID或状态");
        }
        oaService.projectFileMoreEndBackStatus(jsonObject);
        return success("操作成功!");
    }

    /**
     * 各阶段评审流程状态回写
     * @param jsonObject
     */
    @Log(title = "外部接口:各阶段评审流程状态回写", businessType = BusinessType.UPDATE,isExternalRequest = true)
    @PostMapping("/projectStageReview")
    public AjaxResult projectStageReview(@RequestBody JSONObject jsonObject){
        if(StringUtils.isBlank(jsonObject.getString("oaId")) || jsonObject.getInteger("status") == null
                || StringUtils.isBlank(jsonObject.getString("oaNo"))  || StringUtils.isBlank(jsonObject.getString("projectListNodeMemberId"))){
            return error("请求参数错误，缺少ID，OA编号或状态");
        }
        oaService.projectStageReview(jsonObject);
        return success("操作成功!");
    }


    /**
     * 项目变更流程状态回写
     * @param jsonObject
     */
    @Log(title = "外部接口:项目变更状态回写", businessType = BusinessType.UPDATE,isExternalRequest = true)
    @PostMapping("/projectModifyProcessStatus")
    public AjaxResult projectModifyProcessStatus(@RequestBody JSONObject jsonObject){
        if(StringUtils.isBlank(jsonObject.getString("oaId")) || jsonObject.getInteger("status") == null
                || StringUtils.isBlank(jsonObject.getString("oaNo")) ){
            return error("请求参数错误，缺少ID，OA编号或状态");
        }
        oaService.projectModifyProcessStatus(jsonObject);
        return success("操作成功!");
    }


    //测试推送oa系统创建流程接口
    @GetMapping("/testPutOa")
    public AjaxResult testPutOa(){
        try {
            JSONObject param = new JSONObject();
            param.put("fd_productModel","model001");//机型
            param.put("fd_projectNo","project007");//项目编码
            param.put("fd_clientName","1");
            param.put("fd_productStage","4");//产品阶段
            param.put("fd_fwVersion","v001");//fw版本
            param.put("fd_scaler","scaler字段值");//scaler字段
            param.put("fd_panelVersion","panel版本");//panel版本
            param.put("fd_powerSupple","power/supple");//电源、适配器
            param.put("fd_productLine","1");//产品线
            param.put("fd_3d0c5901c43182_text","梁健行");//项目经理
            param.put("fd_3d0f528680fa76_text","周俊强");//研发总监
            param.put("fd_3d0f52afc0279a_text","张毅");//产品经理
            param.put("fd_3d0f52cab1c2f6_text","邓兴邦");//DQA主管
            JSONArray detail = new JSONArray();//明细表数据

            String fileName="fd_list.";
            for (int i = 0; i < 3; i++) {
                JSONObject detailRow = new JSONObject();//明细表数据行
                detailRow.put(fileName+"fd_table_category","FW");//fw版本
                detailRow.put(fileName+"fd_table_grade","A");//问题等级
                detailRow.put(fileName+"fd_table_problemDesc","原因描述"+i);//原因描述
                detailRow.put(fileName+"fd_table_rootCause","rootCause"+i);//rootCause
                detailRow.put(fileName+"fd_table_rdNo_text","尹鸽");//研发名称
                detailRow.put(fileName+"fd_table_correctiveAction","correctiveAction"+i);
                detailRow.put(fileName+"fd_table_presentDate","2024-06-01");//问题提出的时间
                detail.add(detailRow);
            }
            param.put("fd_list",detail);
            //"测试waive单流程的创建(restTemplate)",
            //String s = oaUtils.addReview2("SS00067", param.toString(), null,null);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("推送waive审批单异常："+e);
            return AjaxResult.error(e.getMessage());
        }
    }
}
